package com.byt.framlib.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.byt.framlib.BuildConfig;
import com.byt.framlib.R;
import com.byt.framlib.basemvp.BasePresenter;
import com.byt.framlib.commonutils.FormatUtil;
import com.byt.framlib.commonutils.NetWorkUtils;
import com.byt.framlib.commonutils.ToastUitl;
import com.byt.framlib.commonutils.permission.PermissionReq;
import com.byt.framlib.commonutils.permission.ResultListener;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.LoadingDialog;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.StatusBarUtil;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.trello.rxlifecycle3.components.support.RxFragment;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * des:基类fragment
 */
public abstract class BaseFragment<P extends BasePresenter> extends RxFragment {

    protected Unbinder mUnbinder;
    protected View rootView;
    protected Activity context;
    protected Bundle mSavedInstanceState;
    protected Disposable mDisposable = null;
    protected CompositeDisposable mCompositeDisposable = null;
    protected RefreshLayout refreshLayout = null;
    protected P mPresenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        context = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(getLayoutResource(), container, false);
        mSavedInstanceState = savedInstanceState;
        mUnbinder = ButterKnife.bind(this, rootView);
        if (rootView.getParent() != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
//        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_DUM_NORMAL);
        mPresenter = initPresenter();
        initView();
        return rootView;
    }

    //获取布局文件
    protected abstract int getLayoutResource();

    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    public abstract P initPresenter();

    //初始化view
    protected abstract void initView();

    /**
     * 添加Subscription
     *
     * @param disposable
     */
    public void addSubscription(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }


    /**
     * 第一次加载
     */
    public void initFristData() {

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * 通过Class跳转界面
     **/
    public void openActivity(Class<?> cls) {
        openActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void openActivityForResult(Class<?> cls, int requestCode) {
        openActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void openActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void openActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }


    /**
     * 回调
     *
     * @param bundle
     */
    public void setResultOk(Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) ;
        intent.putExtras(bundle);
        context.setResult(Activity.RESULT_OK, intent);
        context.finish();
    }

    /**
     * 开启加载进度条
     */
    public void startProgressDialog() {
        LoadingDialog.showDialogForLoading(getActivity());
    }

    /**
     * 开启加载进度条
     *
     * @param msg
     */
    public void startProgressDialog(String msg) {
        LoadingDialog.showDialogForLoading(context, msg, true);
    }

    /**
     * 停止加载进度条
     */
    public void stopProgressDialog() {
        LoadingDialog.cancelDialogForLoading();
    }


    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUitl.showShort(text);
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUitl.showShort(resId);
    }

    /**
     * 长时间显示Toast提示(来自res)
     **/
    public void showLongToast(int resId) {
        ToastUitl.showLong(resId);
    }

    /**
     * 长时间显示Toast提示(来自String)
     **/
    public void showLongToast(String text) {
        ToastUitl.showLong(text);
    }


    public void showToastWithImg(String text, int res) {
        ToastUitl.showToastWithImg(text, res);
    }

    /**
     * 网络访问错误提醒
     */
    public void showNetErrorTip() {
        ToastUitl.showToastWithImg(getText(R.string.net_error).toString(), R.drawable.ic_wifi_off);
    }

    public void showNetErrorTip(String error) {
        ToastUitl.showToastWithImg(error, R.drawable.ic_wifi_off);
    }

    /**
     * 获取当前Fragment状态
     *
     * @return true为正常 false为未加载或正在删除
     */
    private boolean getStatus() {
        return (isAdded() && !isRemoving());
    }

    @Override
    public void onDestroyView() {
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
            mCompositeDisposable.clear();
            RxBus.getDefault().removeAllStickyEvents();
        }
        if (mDisposable != null) {
            if (!mDisposable.isDisposed()) {
                mDisposable.dispose();
                RxBus.getDefault().removeAllStickyEvents();
            }
        }
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        //debug版本不统计crash
        if (!BuildConfig.DEBUG) {
//            MobclickAgent.onPageStart("BaseFragment");
//            MobclickAgent.onResume(context);
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        //debug版本不统计crash
        if (!BuildConfig.DEBUG) {
//            MobclickAgent.onPageEnd("BaseFragment");
//            MobclickAgent.onPause(getActivity());
        }
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
        super.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionReq.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void showErrorView(String msg, LoadingTip loadingTip) {
        if (!TextUtils.isEmpty(msg)) {
            loadingTip.setTips(msg);
        }
        if (!NetWorkUtils.IsNetWorkEnable(context)) {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.error);
        } else {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.sereverError);
        }
    }

    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
     */
    @SuppressLint("MissingPermission")
    public void callPhone(String phoneNum) {
        PermissionReq.with(this)
                .permissions(Manifest.permission.CALL_PHONE)
                .result(new ResultListener() {
                    @Override
                    public void onGranted() {
                        showPhonDialog(phoneNum);
                    }

                    @Override
                    public void onDenied() {
                        showShortToast("请开启电话权限");
                    }
                }).request();
    }

    private void showPhonDialog(String phoneNum) {
        if (!TextUtils.isEmpty(phoneNum) && FormatUtil.isMobileNO(phoneNum)) {
            @SuppressLint("ResourceType")
            NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(context)
                    .setTitleVisible(false)
                    .setContentText(phoneNum)
                    .setContentTextSize(18)
                    .setContentTextColor(R.color.color_333333)
                    .setRightButtonText("呼叫")
                    .setRightButtonTextColor(R.color.color_main)
                    .setOnclickListener(new DialogOnClickListener() {
                        @Override
                        public void clickLeftButton(View view) {
                        }

                        @Override
                        public void clickRightButton(View view) {
                            Intent intent = new Intent(Intent.ACTION_CALL);
                            Uri data = Uri.parse("tel:" + phoneNum);
                            intent.setData(data);
                            startActivity(intent);
                        }
                    }).build();
            normalAlertDialog.show();
        } else {
            showShortToast("请输入正确的手机号");
        }
    }

    protected void setRefreshLayout(RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
    }

    //获取状态栏的高度
    public int getTitleHight() {
        int statusBarHeight1 = -1;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }
}